// LEDArray.cpp : implementation file
//

#include "stdafx.h"
#include "Measure.h"
#include "LEDArray.h"


// CLEDArray

IMPLEMENT_DYNAMIC(CLEDArray, CStatic)

CLEDArray::CLEDArray()
{
  num_rows_ = 1;
  num_cols_ = 1;
  oks_.resize(1);
  oks_[0].resize(1);
}

CLEDArray::~CLEDArray()
{
}


BEGIN_MESSAGE_MAP(CLEDArray, CStatic)
END_MESSAGE_MAP()



// CLEDArray message handlers




void CLEDArray::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
  CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
  ENSURE(pDC);

  CBrush brush(RGB(0, 0, 0));
  pDC->FillRect(&(lpDrawItemStruct->rcItem), &brush);

  int width   = lpDrawItemStruct->rcItem.right - lpDrawItemStruct->rcItem.left;
  int height  = lpDrawItemStruct->rcItem.bottom - lpDrawItemStruct->rcItem.top;

  int drawWidth   = max(0, (width-3*(num_cols_+1))/num_cols_);
  int drawHeight  = max(0, (height-3*(num_rows_+1))/num_rows_);
  int drawSize    = min(drawWidth, drawHeight);

  if (drawSize==0) {
    return;
  }

  CRect rcDraw;
  CString strNum;
  CBrush okBrush(RGB(0, 255, 0));
  CBrush ngBrush(RGB(255, 0, 0));
  for (int r=0; r<num_rows_; ++r) {
    rcDraw.top    = r*(drawHeight+3) + 3;
    rcDraw.bottom = rcDraw.top + drawHeight;
    for (int c=0; c<num_cols_; ++c) {
      rcDraw.left = c*(drawWidth+3) + 3;
      rcDraw.right = rcDraw.left + drawWidth;
      strNum.Format(_T("%d"), r*num_cols_+c+1);
      if (oks_[r][c]) {
        pDC->FillRect(rcDraw, &okBrush);
      } else {
        pDC->FillRect(rcDraw, &ngBrush);
      }
      pDC->SetBkMode(TRANSPARENT);
      pDC->DrawText(strNum, rcDraw, DT_SINGLELINE|DT_CENTER|DT_VCENTER);
    }
  }
}


void CLEDArray::PreSubclassWindow()
{
  ModifyStyle(SS_TYPEMASK, SS_OWNERDRAW);
  CStatic::PreSubclassWindow();
}

void CLEDArray::SetRowCol(int numRows, int numCols)
{
  if (numRows<1 || numCols<1) {
    return;
  }

  if (num_rows_==numRows && num_cols_==numCols) {
    return;
  }

  num_rows_ = numRows;
  num_cols_ = numCols;

  oks_.clear();
  oks_.resize(numRows);
  for (int r=0; r<numRows; ++r) {
    oks_[r].resize(num_cols_, FALSE);
  }

  Invalidate(FALSE);
}

void CLEDArray::SetOk(int row, int col, BOOL ok)
{
  if (row<0 || row>=num_rows_) {
    return;
  }

  if (col<0 || col>=num_cols_) {
    return;
  }

  oks_[row][col] = ok;
  Invalidate(FALSE);
}

void CLEDArray::Reset(void)
{
  for (int r=0; r<num_rows_; ++r) {
    for (int c=0; c<num_cols_; ++c) {
      oks_[r][c] = FALSE;
    }
  }

  Invalidate(FALSE);
}

void CLEDArray::Copy(const CLEDArray& srcArray)
{
  SetRowCol(srcArray.num_rows_, srcArray.num_cols_);

  for (int r=0; r<num_rows_; ++r) {
    for (int c=0; c<num_cols_; ++c) {
      oks_[r][c] = srcArray.oks_[r][c];
    }
  }

  Invalidate(FALSE);
}
